#include <iostream>
#include <string>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define User 2
#define Creator 1
#define DefaultFd -1
#define Size 1024
#define Read O_RDONLY
#define Write O_WRONLY

const char* PATH = "/home/chen/Code/namepipe/pipe";
const char* QUIT = "quit";

class namepipe
{
private:
    bool OpenNamePipe(mode_t mode)
    {
        _fd = open(_fifo_path.c_str(), mode);
        if(_fd < 0)
        {
            std::cout << "open for write unsucess" << std::endl;
            return false;
        }

        return true;
    }

public:
    namepipe(const std::string& path,int role)
        :_fifo_path(path),ID(role),_fd(DefaultFd)
    {
        if(role == Creator)
        {
            int f = mkfifo(PATH,0666);
            if(f < 0)
            {
                std::cerr << "mkfifo erro: " << errno << std::endl; 
            }
            std::cout << "create namepipe sucess" << std::endl;
        }
    }

    ~namepipe()
    {
        if(_fd != DefaultFd)
        {
            close(_fd);
        }
        if(ID == Creator)
        {
            int res = unlink(_fifo_path.c_str());
            if (res != 0)
            {
                perror("unlink");
            }
            std::cout << "creater unlink named pipe" << std::endl;
        }
    }

    bool OpenForWrite()
    {
        return OpenNamePipe(Write);
    }

    bool OpenForRead()
    {
        return OpenNamePipe(Read);
    }

    int SendMeassage(const std::string& in)
    {
        return write(_fd, in.c_str(), in.size());
    }

    int GetMeassage(std::string* out)
    {
        char buf[Size] = {0};
        ssize_t n = read(_fd, buf, sizeof(buf));
        if(n > 0)
        {
            buf[n] = 0;
            (*out) = buf;
        }

        return n;
    }

private:
    std::string _fifo_path;
    int ID;
    int _fd;
};